
import 'dart:io';

import 'package:flutter/services.dart';
import 'package:flutter_aliplayer/flutter_aliplayer_factory.dart';

import '../service/launchservice/launchservice.dart';
import '../service/request_manager.dart';
import '../tool/player/model/playauth_model.dart';
enum VideoAuthType {
  unknown,
  online,
  download,
  offline
}
class AliPlayerManger {
  /// 单例对象
  static AliPlayerManger? _instance;

  /// 内部构造方法，可避免外部暴露构造函数，进行实例化
  AliPlayerManger._internal();

  /// 工厂构造方法，这里使用命名构造函数方式进行声明
  factory AliPlayerManger.getInstance() => _getInstance();

  /// 获取单例内部方法
  static _getInstance() {
    // 只能有一个实例
    if (_instance == null) {
      _instance = AliPlayerManger._internal();
      _instance?._initLicense();
      _instance?._loadEncrypted();
    }
    return _instance;
  }



  _loadEncrypted() async {
    if (Platform.isAndroid) {
      var bytes = await rootBundle.load("assets/encryptedApp.dat");
      // getExternalStorageDirectories
      FlutterAliPlayerFactory.initService(bytes.buffer.asUint8List());
    } else if (Platform.isIOS) {
      var bytes = await rootBundle.load("assets/encryptedApp_ios.dat");
      FlutterAliPlayerFactory.initService(bytes.buffer.asUint8List());
    }
  }


  _initLicense() {
    if (Platform.isIOS) {
      FlutterAliPlayerFactory.initLicenseServiceForIOS();
    } else {
      // 不需要
    }
  }






  Future<PlayAuthModel?> requestPlayAuth({required int kid, required VideoAuthType authType}) async{
    final url = LaunchService.getInstance().config?.api?.videoPlayAuth;
    if (url != null) {
      final response = await RequestManager
          .getInstance()
          .dio
          .get(url!, queryParameters: {"kid": kid, "useType": authType.index});
      final data = response.data as Map<String, dynamic>;
      final dict = data["data"] as Map<String, dynamic>;
      final model = PlayAuthModel.fromJson(dict);
      return model;
    }
    return null;
  }






}
